package com.example.jpa.enums;

import org.springframework.core.convert.converter.Converter;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/12/12 18:49
 */
public class IntegerCodeToGenderEnumConverter implements Converter<Integer, GenderEnum>
{
    private Map<Integer, GenderEnum> enumMap = new HashMap<>();

    public IntegerCodeToGenderEnumConverter()
    {
        for (GenderEnum genderEnum : GenderEnum.values())
        {
            enumMap.put(genderEnum.getCode(), genderEnum);
        }
    }

    @Override
    public GenderEnum convert(Integer source)
    {
        GenderEnum genderEnum = enumMap.get(source);
        if (Objects.isNull(genderEnum))
        {
            throw new IllegalArgumentException("无法匹配对应的枚举类型");
        }
        return genderEnum;

    }
}
